import {
  CloseCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import {
  Button,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
} from 'antd';
import moment from 'moment';
import { useEffect, useState } from 'react';
import styles from './index.less';
const { TextArea } = Input;
const { Option } = Select;

import RateItem from '../component/RateItem';
const { confirm } = Modal;

const dataMat = 'YYYY/MM/DD';
const DrawerKr = (props) => {
  const [form] = Form.useForm();
  const { visible, onCloseVisible, k, okrDetailPoList = [], isDetailFlag, status, isEdit, isLeader } = props;
  const [list, setList] = useState([0]);
  const [id, setId] = useState(0);
  const [itemObj, setItemObj] = useState({});

  useEffect(() => {
    if (okrDetailPoList.length > 0) {
      const nums = okrDetailPoList.map((val, index) => {
        return index + 1;
      });
      setList(nums);
      setId(nums.length);
      const lis = okrDetailPoList.map((item, index) => {
        return {
          [`id${index+1}`]: item.id,
          [`confidence${index + 1}`]: item.confidence,
          [`detail${index + 1}`]: item.detail,
          [`endTime${index + 1}`]: item.endTime,
          [`krname${index + 1}`]: item.krname,
          [`krweight${index + 1}`]: item.krweight,
          [`krprocess${index + 1}`]: item.krprocess,
          [`krendscore${index + 1}`]: item.krendscore,
          [`krscore${index + 1}`]: item.krscore,
        };
      });
      let objs = {};
      lis.map((item, index) => {
        objs = Object.assign({}, objs, item);
      });
      setItemObj(objs);
    }
  }, []);

  const onClose = () => {
    onCloseVisible(false);
  };
  const add = () => {
    if(list.length >= 5){
      message.warning('每个OKR建议最多5个O，请合理分配')
      return;
    }
    let newId = id + 1;
    list.push(newId);
    setId(newId);
    setList(JSON.parse(JSON.stringify(list)));
  };
  const deleteList = (k) => {
    const newlist = list.filter((v) => v !== k);
    setList(JSON.parse(JSON.stringify(newlist)));
  };
  const save = () => {
    form
      .validateFields()
      .then((values) => {
        const listN = list.map((k) => {
          return {
            id: values[`id${k}`] || '',
            confidence: values[`confidence${k}`],
            detail: values[`detail${k}`],
            krname: values[`krname${k}`],
            krweight: values[`krweight${k}`],
            endTime: values[`endTime${k}`].format(dataMat),
            krprocess: values[`krprocess${k}`] || 0,
            krendscore: values[`krendscore${k}`] || 0,
            krscore: values[`krscore${k}`] || 0
          };
        });
        const sum = judgeWeight(listN);
        if (sum != 100) {
          message.error('所有KR总和需等于100，请检查，重新填写权重！');
        } else {
          const filterArr = judgeWeight2(listN);
          if (filterArr.length > 0) {
            confirm({
              title: '部分KR的权重超过50，确定要继续保存吗？',
              icon: <ExclamationCircleOutlined />,
              content: '',
              onOk() {
                props.updateKrList(listN);
                onClose();
              },
              onCancel() {},
            });
          } else {
            props.updateKrList(listN);
            onClose();
          }
        }
      })
      .catch((errinfo) => {
        console.log(errinfo, '--errinof');
      });
  };
  const judgeWeight = (arr) => {
    const newArr = arr.map((item) => item.krweight);
    const sum = newArr.reduce((prev, curr) => {
      return Number(prev) + Number(curr);
    });
    return sum;
  };
  const judgeWeight2 = (arr) => {
    const newArr = arr.filter((item) => Number(item.krweight) > 50);
    return newArr;
  };
  const checkWeight = (rule, value, callback) => {
    let regx = /^([1-9][0-9]{0,1}|100|0)$/;
    if (value) {
      if (!regx.test(value)) {
        callback('请输入数字');
      } else {
        callback();
      }
    } else {
      callback();
    }
  };
  const disabled =  Number(status) > 1; //普通不能编辑的字段权限
  const disabledScore = !(isEdit && Number(status) == 2); // 自评分权限
  const disableEndScore = !(isEdit && Number(status) == 3); // 最终分权限
  return (
    <>
      <Drawer
        title="KR列表"
        width={720}
        onClose={onClose}
        visible={visible}
        maskClosable={false}
        bodyStyle={{ paddingBottom: 80 }}
        placement={'right'}
      >
        <Form form={form}>
          {list.length > 0 &&
            list.map((k, index) => {
              return (
                <div
                  key={`${k}`}
                  className={styles.kr_list_wrap}
                  style={{ position: 'relative', width: '90%' }}
                >
                  {list.length > 1 && !disabled &&(
                    <span
                      className={styles.delete_wrap}
                      onClick={() => {
                        deleteList(k);
                      }}
                    >
                      <CloseCircleOutlined
                        style={{ fontSize: '16px', color: '#1790ff' }}
                      />
                    </span>
                  )}
                  <Form.Item
                    label={`KR${index + 1}`}
                    name={`id${k}`}
                    hidden={true}
                    initialValue={
                      itemObj[`id${k}`] ? itemObj[`id${k}`] : ''
                    }
                  >
                    <TextArea
                      disabled={disabled}
                      allowClear
                      autoSize={{ minRows: 1 }}
                      placeholder="id"
                      maxLength={100}
                    />
                  </Form.Item>
                  <Form.Item
                    label={`KR${index + 1}`}
                    name={`krname${k}`}
                    rules={[{ required: true, message: '必填' }]}
                    initialValue={
                      itemObj[`krname${k}`] ? itemObj[`krname${k}`] : ''
                    }
                  >
                    <TextArea
                      disabled={disabled}
                      allowClear
                      autoSize={{ minRows: 1 }}
                      placeholder="请输入KR的描述,不能超过100字"
                      maxLength={100}
                    />
                  </Form.Item>
                  <Form.Item
                    label={`说明`}
                    name={`detail${k}`}
                    initialValue={
                      itemObj[`detail${k}`] ? itemObj[`detail${k}`] : ''
                    }
                  >
                    <TextArea
                      disabled={disabled}
                      allowClear
                      autoSize={{ minRows: 1 }}
                      placeholder="请输入KR的详细说明,不能超过300字"
                      maxLength={300}
                    />
                  </Form.Item>
                  {/* 进度--详情展示 */}
                  {/* <Form.Item
                        label={`Path`}
                        name={`path${k}`} 
                        rule={[{required: true, message: '必填'}]}
                        >
                            <TextArea autoSize={{ minRows: 1 }}  placeholder="请输入KR的Path,不能超过3000字" maxLength={3000} />
                        </Form.Item> */}
                  <Row gutter={20}>
                    <Col span={9}>
                      <Form.Item
                        label={`完成时间`}
                        name={`endTime${k}`}
                        rules={[{ required: true, message: '必填' }]}
                        initialValue={
                          itemObj[`endTime${k}`]
                            ? moment(itemObj[`endTime${k}`], dataMat)
                            : ''
                        }
                      >
                        <DatePicker disabled={disabled} placeholder="完成时间" />
                      </Form.Item>
                    </Col>
                    <Col span={9}>
                      <Form.Item
                        label={`信心指数`}
                        name={`confidence${k}`}
                        rules={[{ required: true, message: '必填' }]}
                        initialValue={
                          itemObj[`confidence${k}`]
                            ? itemObj[`confidence${k}`]
                            : ''
                        }
                      >
                        <RateItem disabled={disabled}></RateItem>
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Form.Item
                        label={`权重`}
                        name={`krweight${k}`}
                        rules={[
                          { required: true, message: '必填' },
                          { validator: checkWeight },
                        ]}
                        initialValue={
                          itemObj[`krweight${k}`] ? itemObj[`krweight${k}`] : ''
                        }
                      >
                        <Input disabled={disabled} placeholder="100" maxLength={3} />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    {isDetailFlag && <Col span={9}>
                      <Form.Item
                        label={`进度`}
                        name={`krprocess${k}`}
                        rules={[{ required: true, message: '必填' },{ validator: checkWeight }]}
                        initialValue={
                          itemObj[`krprocess${k}`] ? itemObj[`krprocess${k}`] : ''
                        }
                      >
                        <Input disabled={disabled} placeholder="100" maxLength={3} />
                      </Form.Item>
                    </Col>}
                    {Number(status) > 1 && <Col span={9}>
                      <Form.Item
                        label={`自评分`}
                        name={`krscore${k}`}
                        rules={[{ required: true, message: '必填' }, { validator: checkWeight }]}
                        initialValue={
                          itemObj[`krscore${k}`] ? itemObj[`krscore${k}`] : ''
                        }
                      >
                        <Input disabled={disabledScore} placeholder="100" maxLength={3} />
                      </Form.Item>
                    </Col>}
                    {Number(status) > 2 && <Col span={6}>
                      <Form.Item
                        label={`最终得分`}
                        name={`krendscore${k}`}
                        rules={[
                          { required: true, message: '必填' },
                          { validator: checkWeight },
                        ]}
                        initialValue={
                          itemObj[`krendscore${k}`] ? itemObj[`krendscore${k}`] : ''
                        }
                      >
                        <Input disabled={disableEndScore} placeholder="100" maxLength={3} />
                      </Form.Item>
                    </Col>}
                  </Row>
                </div>
              );
            })}
        </Form>
        <Row></Row>
        <Row
          style={{
            position: 'absolute',
            width: '690px',
            padding: '20px 0',
            bottom: '0px',
            background: '#ffffff',
            display: 'flex',
            justifyContent: 'center',
          }}
        >
          <Button type="primary" onClick={add} disabled={disabled} style={{ marginRight: '10px' }}>
            Add KR
          </Button>
          <Button type="primary" onClick={save} style={{ marginRight: '10px' }}>
            保存
          </Button>
          <Button onClick={onClose} style={{ marginRight: '10px' }}>
            取消
          </Button>
        </Row>
      </Drawer>
    </>
  );
};

export default DrawerKr;
